package reznic.ga.tracker;

import java.io.IOException;
import reznic.ga.tracker.interfaces.ProtocolBuilder;
import reznic.ga.tracker.objects.Config;
import reznic.ga.tracker.objects.RequestData;
import reznic.ga.tracker.utils.StringUtils;

/**
 *
 * @author Reznic Alexandru <reznic.a@gmail.com>
 */
public class ProtocolBuilderV1 implements ProtocolBuilder {

    private static final String URL = "http://www.google-analytics.com/collect?";
    private final Config config;

    public ProtocolBuilderV1(Config config) {
        this.config = config;
    }

    @Override
    public String build(RequestData data) throws IOException {
        StringBuilder buf = new StringBuilder(URL);
        buf.append("v=1");
        buf.append("&tid=").append(config.getTrackID());
        buf.append("&cid=").append(data.getVisitor().getId());

        buf.append("&de=").append(config.getEncoding());
        if (data.getVisitor().getScreenSize() != null) {
            buf.append("&sr=").append(data.getVisitor().getScreenSize());
        }
        if (data.getVisitor().getUserLanguage() != null) {
            buf.append("&ul=").append(data.getVisitor().getUserLanguage());
        }
        if (data.getPageview() != null) {
            buf.append("&t=").append(RequestData.HIT.PAGEVIEW.toString());
            buf.append(data.getPageview().buildURL());
        } else if (data.getEvent() != null) {
            buf.append("&t=").append(RequestData.HIT.EVENT.toString());
            buf.append(data.getEvent().buildURL());
        } else if (data.getItem() != null) {
            buf.append("&t=").append(RequestData.HIT.ITEM.toString());
            buf.append(data.getItem().buildURL());
        } else if (data.getMobileApp() != null) {
            buf.append("&t=").append(RequestData.HIT.APPVIEW.toString());
            buf.append(data.getMobileApp().buildURL());
        }

        return buf.toString();
    }

    @Override
    public void reset() {
    }
}
